<?php
/**
 * Here is your custom functions.
 */

use support\spark\model\system\AdminUser;


const SUCCESS = 'layui-icon-ok-circle';
const ERROR = 'layui-icon-close-fill';

if (!function_exists('sparkSuccess')) {
    /**
     * api返回
     */
    function sparkSuccess($data)
    {
        return \support\spark\Response::success($data);
    }
}

if (!function_exists('checkenv')) {
    /**
     * 检测环境变量
     */
    function checkenv()
    {
        $items = [];
        $items['php'] = PHP_VERSION;
        $items['mysqli'] = extension_loaded('mysqli');
        $items['redis'] = extension_loaded('redis');
        $items['curl'] = extension_loaded('curl');
        $items['fileinfo'] = extension_loaded('fileinfo');
        $items['exif'] = extension_loaded('exif');
        $items['gd'] = extension_loaded('gd');

        return $items;
    }
}

if (!function_exists('check_dirfile')) {
    /**
     * 检测读写环境
     */
    function check_dirfile()
    {
        $items = array(
            array('dir', SUCCESS, SUCCESS, './'),
            array('dir', SUCCESS, SUCCESS, './public'),
            array('dir', SUCCESS, SUCCESS, './runtime'),
            // array('dir', SUCCESS, SUCCESS, './test/1.txt'),
        );

        foreach ($items as &$value) {

            $item = run_path($value[3]);

            // 写入权限
            if (!is_writable($item)) {
                $value[1] = ERROR;
            }
            // 读取权限
            if (!is_readable($item)) {
                $value[2] = ERROR;
            }
        }

        return $items;
    }
}

if (!function_exists('parse_array_ini')) {
    /**
     * 解析数组到ini文件
     * @param array $array 数组
     * @param string $content 字符串
     * @return string    返回一个ini格式的字符串
     */
    function parse_array_ini($array, $content = '')
    {

        foreach ($array as $key => $value) {
            if (is_array($value)) {
                // 分割符PHP_EOL
                $content .= PHP_EOL . '[' . $key . ']' . PHP_EOL;
                foreach ($value as $field => $data) {
                    $content .= $field . ' = ' . $data . PHP_EOL;
                }

            } else {
                $content .= $key . ' = ' . $value . PHP_EOL;
            }
        }

        return $content;
    }
}

if (!function_exists('write_file')) {
    /**
     * 数据写入文件
     * @param string $file 文件路径
     * @param string $content 文件数据
     * @return content
     */
    function write_file($file, $content = '')
    {
        $dir = dirname($file);
        if (!is_dir($dir)) {
            mkdir($dir);
        }
        return @file_put_contents($file, $content);
    }
}
/**
 * 当前管理员id
 * @return integer|null
 */
function admin_id(): ?int
{
    return session('admin.id');
}

/**
 * 当前管理员
 * @param null|array|string $fields
 * @return array|mixed|null
 */
function admin($fields = null)
{
    refresh_admin_session();
    if (!$admin = session('admin')) {
        return null;
    }
    if ($fields === null) {
        return $admin;
    }
    if (is_array($fields)) {
        $results = [];
        foreach ($fields as $field) {
            $results[$field] = $admin[$field] ?? null;
        }
        return $results;
    }
    return $admin[$fields] ?? null;
}

/**
 * 当前登录用户id
 * @return integer|null
 */
function user_id(): ?int
{
    return session('user.id');
}

/**
 * 当前登录用户
 * @param null|array|string $fields
 * @return array|mixed|null
 */
function user($fields = null)
{
    refresh_user_session();
    if (!$user = session('user')) {
        return null;
    }
    if ($fields === null) {
        return $user;
    }
    if (is_array($fields)) {
        $results = [];
        foreach ($fields as $field) {
            $results[$field] = $user[$field] ?? null;
        }
        return $results;
    }
    return $user[$fields] ?? null;
}

/**
 * 刷新当前管理员session
 * @param bool $force
 * @return void
 */
function refresh_admin_session(bool $force = false)
{
    if (!$admin_id = admin_id()) {
        return null;
    }
    $time_now = time();
    // session在2秒内不刷新
    $session_ttl = 2;
    $session_last_update_time = session('admin.session_last_update_time', 0);
    if (!$force && $time_now - $session_last_update_time < $session_ttl) {
        return null;
    }
    $session = request()->session();
    $admin = AdminUser::find($admin_id);
    if (!$admin) {
        $session->forget('admin');
        return null;
    }
    $admin = $admin->toArray();
    unset($admin['password']);
    // 账户被禁用
    if ($admin['status'] == 2) {
        $session->forget('admin');
        return;
    }
    //  $admin['roles'] = AdminRole::where('admin_id', $admin_id)->pluck('role_id')->toArray();
    $admin['roles'] = $admin['role_id'];
    $admin['session_last_update_time'] = $time_now;
    $session->set('admin', $admin);
}


/**
 * 刷新当前用户session
 * @param bool $force
 * @return void
 */
function refresh_user_session(bool $force = false)
{
    if (!$user_id = user_id()) {
        return null;
    }
    $time_now = time();
    // session在2秒内不刷新
    $session_ttl = 2;
    $session_last_update_time = session('user.session_last_update_time', 0);
    if (!$force && $time_now - $session_last_update_time < $session_ttl) {
        return null;
    }
    $session = request()->session();
    $user = AdminUser::find($user_id);
    if (!$user) {
        $session->forget('user');
        return null;
    }
    $user = $user->toArray();
    unset($user['password']);
    $user['session_last_update_time'] = $time_now;
    $session->set('user', $user);
}

/**
 * 生成密码
 * @param $password
 * @param $salt
 * @return string
 */
function makePassword($password, $salt = '')
{

    if (empty($salt)) {
        $salt = config('shop.salt');
    }

    return sha1(md5(md5($password . $salt)));
}

/**
 * 生成子孙树
 * @param $data
 * @return array
 */
function makeTree($data)
{

    $res = [];
    $tree = [];

    // 整理数组
    foreach ($data as $key1 => $vo1) {
        $res[$vo1['id']] = $vo1;
    }
    unset($data);

    // 查询子孙
    foreach ($res as $key2 => $vo2) {
        if ($vo2['pid'] != 0) {
            $res[$vo2['pid']]['child'][] = &$res[$key2];
        }
    }
    // 去除杂质
    foreach ($res as $key3 => $vo3) {
        if (isset($vo3['pid']) && $vo3['pid'] == 0) {
            $tree[] = $vo3;
        }
    }
    unset($res);

    return $tree;
}

function now()
{
    return date('Y-m-d H:i:s');
}

/**
 * 模型内统一数据返回
 * @param $code
 * @param string $msg
 * @param array $data
 * @return array
 */

if (!function_exists('dataReturn')) {

    function dataReturn($code, $msg = 'success', $data = [])
    {
        return ['code' => $code, 'data' => $data, 'msg' => $msg];
    }
}


function getConfByType($type)
{
    try {

        $configModel = new \support\spark\model\system\SysSetting();
        $config = $configModel->where('type', $type)->get()->toArray();
        $formatConfig = [];
        foreach ($config as $vo) {
            $formatConfig[$vo['key']] = $vo['value'];
        }

        return $formatConfig;
    } catch (\Throwable $e) {
        return [];
    }
}

function toArray($obj)
{

    return json_decode(json_encode($obj), true);
}

function returnPage(object $list)
{
    $data['data'] = $list->items();
    $data['total'] = $list->total();
    return $data;

}

/**
 * 检测是否安装了某个插件
 * @param $flag
 * @return bool
 */
function hasInstalled($flag)
{
    $info = (new \support\spark\model\system\Plugins())->getInfoByWhere(['name' => $flag,'status'=>2]);
    return !empty($info);

}

/**
 * 生成订单号
 * @param $business
 * @return string
 */
function makeOrderNo($business)
{
    return $business . date('YmdHis') . GetNumberCode(6);
}


/**
 * 随机数生成生成
 * @param int $length
 * @return string
 */
function GetNumberCode($length = 6)
{
    $code = '';
    for ($i = 0; $i < intval($length); $i++) {
        $code .= rand(0, 9);
    }

    return $code;
}

/**
 * 名字加密
 * @param $name
 * @return string
 */
function encryptName($name)
{
    $encryptName = '';
    // 判断是否包含中文字符
    if (preg_match("/[\x{4e00}-\x{9fa5}]+/u", $name)) {
        // 按照中文字符计算长度
        $len = mb_strlen($name, 'UTF-8');
        // echo '中文';
        if ($len >= 3) {
            // 三个字符或三个字符以上掐头取尾，中间用*代替
            $encryptName = mb_substr($name, 0, 1, 'UTF-8') . str_repeat('*', $len - 2) . mb_substr($name, -1, 1, 'UTF-8');
        } elseif ($len === 2) {
            //两个字符
            $encryptName = mb_substr($name, 0, 1, 'UTF-8') . '*';
        }
    } else {
        // 按照英文字串计算长度
        $len = strlen($name);
        // echo 'English';
        if ($len >= 3) {
            // 三个字符或三个字符以上掐头取尾，中间用*代替
            $encryptName = substr($name, 0, 1) . str_repeat('*', $len - 2) . substr($name, -1);
        } elseif ($len === 2) {
            // 两个字符
            $encryptName = substr($name, 0, 1) . '*';
        }
    }

    return $encryptName;
}



if (!function_exists('getUserInfo')) {
    /**
     * 获取用户信息
     */
    function getUserInfo()
    {
        return \Tinywan\Jwt\JwtToken::getUser();
    }
}
/**
 * 插件中获取用户信息
 * @return array
 */
function getUserInfoInPlugin() {

    $sessionConfig = include run_path() . 'index' . '/' . 'config' . '/' . 'session.php';
    $sessionConfig['path'] = runtime_path() . 'index' . '/' . 'session' . '/';

    preg_match('/sparkShop=[0-9a-z]{0,32}/', request()->header()['cookie'], $matches);
    $sessionId = str_replace($sessionConfig['name'] . '=', '', str_replace('sparkShop=', '', $matches[0]));
    $content = (new File(App(), $sessionConfig))->read($sessionId);
    $userInfo = unserialize($content);

    if (empty($userInfo)) {
        return [];
    }

    return [
        'id' => $userInfo['home_user_id'],
        'name' => $userInfo['home_user_name'],
        'avatar' => $userInfo['home_user_avatar']
    ];
}
if (!function_exists('event')) {
    /**
     * 发布事件
     */
    function event($event_name,$data=[])
    {
       return \Webman\Event\Event::emit($event_name, $data);
    }
}

/**
 * 删除目录
 * @param $dir
 * @return bool
 */
function delDir($dir) {
    // 先删除目录下的文件：
    $dh = opendir($dir);
    while ($file = readdir($dh)) {
        if ($file != "." && $file != "..") {

            $fullPath = $dir . "/" . $file;
            if (!is_dir($fullPath)) {
                unlink($fullPath);
            } else {
                delDir($fullPath);
            }
        }
    }

    closedir($dh);
    // 删除当前文件夹：
    if (rmdir($dir)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 格式化短信数据
 * @param $param
 * @return array
 */
function formatSmsData($param)
{
    $code = makeRandNumber(6);
    return [
        'accessKeyId' => $param['access_key_id'],
        'accessKeySecret' => $param['access_key_secret'],
        'signName' => $param['sign_name'],
        'templateCode' => $param['templateCode'],
        'phone' => $param['phone'],
        'code' => json_encode(['code' => $code])
    ];
}


/**
 * 生成随机验证码
 * @param $len
 * @return int
 */
function makeRandNumber($len)
{
    $start = pow(10, $len - 1);
    $end = pow(10, $len) - 1;

    return rand($start, $end);
}
